﻿namespace UFIDA.U9C.Cust.ZLZ.RedARBP
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using UFIDA.U9.AR.ARBill;
    using UFIDA.U9.CBO.FI.DTOs;
    using UFIDA.U9.SM.Ship;
    using UFIDA.U9.SM.SO;
    using UFIDA.U9.TI.SaleInvoice;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.PL.Engine.Cache;
    using UFSoft.UBF.Util.Context;

    /// <summary>
    /// Operation partial 
    /// </summary>	
    public partial class Operation
    {
        internal BaseStrategy Select()
        {
            return new OperationImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class OperationImpementStrategy : BaseStrategy
    {
        public OperationImpementStrategy() { }

        public override object Do(object obj)
        {
            Operation bpObj = (Operation)obj;
            if (bpObj == null)
            {
                throw new NotImplementedException("参数为空");
            }
            //查询销售订单对应的未红冲应收单
            long soid = Convert.ToInt64(bpObj.SOID);
            UFIDA.U9.SM.SO.SO so = UFIDA.U9.SM.SO.SO.Finder.FindByID(soid);
            var solines = so.SOLines.OfType<SOLine>();

            List<long> arlist = RedARBySOLine(solines);
            return new ReturnDto() { Code = 0, Message = $"红冲{arlist.Count}条应收单" };
        }
        /// <summary>
        /// 根据销售订单行 红冲应收
        /// </summary>
        /// <param name="modifiedLines"></param>
        public static List<long> RedARBySOLine(IEnumerable<UFIDA.U9.SM.SO.SOLine> listModifiedSoline)
        {
            List<ARBillLine> ARBillLines = new List<ARBillLine>();
            //var listModifiedSoline = modifiedLines.Where(p => p.NewValue != p.OldValue);
            //通过销售变更单查出销售订单行
            //string shiplineids = string.Join(",", listModifiedSoline.Select(p => p.SOLine));
            string shiplineids = string.Join(",", listModifiedSoline.Select(p => p.ID));
            ////通过销售订单行查询出货单行
            List<ShipLine> shiplines = ShipLine.Finder.FindAll($"SOLinekey in ({shiplineids})").OfType<ShipLine>().ToList();
            if (shiplines == null || shiplines.Count <= 0) { return new List<long>(); }
            //根据出货单查询应收单行信息
            var arbills = ARBillLine.Finder.FindAll($"SrcBillLineID in ({string.Join(",", shiplines.Select(p => p.ID))})").OfType<ARBillLine>();
            if (arbills.Any())
            {
                //通过应收单行查询销售发票信息
                var saleInvoiceDocIndexs = SaleInvoiceDocIndex.Finder.FindAll($"SourceBillNo in ({string.Join(",", arbills.Select(p => "'" + p.ARBillHead.DocNo + "'"))})").OfType<SaleInvoiceDocIndex>();
                if (saleInvoiceDocIndexs.Any())
                    ARBillLines.AddRange(arbills.Where(p => !saleInvoiceDocIndexs.Select(t => t.SourceBillNo).Contains(p.ARBillHead.DocNo)));
                else
                    ARBillLines.AddRange(arbills);
            }

            //红冲应收
            //应收单红冲批操作
            U9.AR.ARBill.Proxy.ARBillRedFlushBatchBPProxy bp = new U9.AR.ARBill.Proxy.ARBillRedFlushBatchBPProxy();
            bp.ARBillHeadDTOs = new List<IDSysVersionDTOData>();
            //不等于 应收贷项通知单
            List<long> headList = ARBillLines.Select(p => p.ARBillHead).Where(p => p.BusinessType.Value != 1 && (p.RedFlushStatus == null || p.RedFlushStatus.Value == -1) && p.Cancel.Canceled == false).Select(p => p.ID).Distinct().ToList();
            bool isFirst = false;
            ARBillHead firstARBillHead = null;
            foreach (long headid in headList)
            {
                if (!isFirst)
                {
                    firstARBillHead = ARBillLines.Select(p => p.ARBillHead).Where(p => p.ID == headid).FirstOrDefault();
                    isFirst = true;
                }
                //headList.Add(headid);
                IDSysVersionDTOData idsys = new IDSysVersionDTOData();
                idsys.EntityID = headid;//应收单头ID
                bp.ARBillHeadDTOs.Add(idsys);//应收单头ID集合
            }
            if (bp.ARBillHeadDTOs.Count == 0)
            {
                return new List<long>();
            }

            bp.AccrueDate = firstARBillHead.AccrueDate;// accrueDate;//立账日期
            bp.PostPeriod = firstARBillHead.PostPeriod.ID;// postPeriod;//记账期间

            ARBillSubmitResultDTOData rstData = bp.Do();
            if (rstData.FailNum > 0)
            {
                throw new Exception($"红冲失败{string.Join("|", rstData.SubmitDetailDTO.Where(p => !string.IsNullOrEmpty(p.FailReason)).Select(p => p.DocNO + ":" + p.FailReason))}");
            }

            //成功            
            ARBillHead.EntityList redlist = ARBillHead.Finder.FindAll("RedFlushStatus=1 and BusinessType=1 and RedFlushBill in (0," + string.Join(",", headList) + ")");
            List<IDSysVersionDTOData> redar = new List<IDSysVersionDTOData>();
            foreach (ARBillHead item in redlist)
            {
                IDSysVersionDTOData idsys = new IDSysVersionDTOData();
                idsys.EntityID = item.ID;//应收单头ID                
                redar.Add(idsys);
            }
            //提交红冲应收
            UFIDA.U9.AR.ARBill.Proxy.ARBillSubmitBatchBPProxy smbp = new U9.AR.ARBill.Proxy.ARBillSubmitBatchBPProxy();
            smbp.ARBillHeadDTOs = redar;
            ARBillSubmitResultDTOData smres = smbp.Do();
            //审核红冲应收单
            UFIDA.U9.AR.ARBill.Proxy.ARBillApproveBatchBPProxy ckbp = new U9.AR.ARBill.Proxy.ARBillApproveBatchBPProxy();
            ckbp.ARBillHeadDTOs = redar;
            ARBillSubmitResultDTOData ckres = ckbp.Do();

            PLCacheManager.DataCache.FlushCache();
            PLCacheManager.ObjectCache.FlushCache();
            return headList;
        }

    }

    #endregion


}